package com.glela.controller;

import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.glela.common.constant.ClientType;
import com.glela.common.constant.CommonConstants;
import com.glela.common.constant.PayTypeEnum;
import com.glela.common.util.NetworkUtil;
import com.glela.common.util.StringUtil;
import com.glela.order.model.request.RequestPayModel;
import com.glela.order.service.OrderPayService;
import com.glela.platform.constant.ErrorEnum;
import com.glela.platform.model.Token;
import com.glela.platform.model.response.ResponseBaseModel;
import com.glela.platform.service.TokenService;
import com.glela.platform.util.ParameterUtils;;

@Controller
@RequestMapping("/orderPay")
public class OrderPayController {

	private static Logger logger = LoggerFactory.getLogger(OrderPayController.class);
	
	@Autowired
	private OrderPayService orderPayService;
	@Autowired
	private TokenService tokenService;
	
	/**
	* **********************************************
	* @Title: goToSettleAccounts 
	* @Description: APP支付接口
	* @param @param request
	* @param @return 
	* @return ResponseEntity<?>
	* @throws	
	* @author NingChongQing	
	* @date 2017年8月25日 下午3:12:56 
	* **********************************************
	 */
	@ResponseBody
	@RequestMapping(value = "/goToSettleAccounts", method = RequestMethod.POST, consumes = "application/json")
	public ResponseEntity<?> goToSettleAccounts(@RequestBody RequestPayModel requestPayModel, HttpServletRequest request) {
		try {
//			if (ParameterUtils.validParams(requestPayModel.getOrderSn(), requestPayModel.getPayType())) {
//				return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20102), HttpStatus.OK);
//			}
			if (ParameterUtils.validParams(requestPayModel.getOrderSn())) {
				return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20102,"缺少订单号"), HttpStatus.OK);
			}
			if (ParameterUtils.validParams( requestPayModel.getPayType())) {
				return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20102,"缺少支付方式"), HttpStatus.OK);
			}
			
			switch (requestPayModel.getPayType()) {
				case 20:
				case 21:
				case 22:
				case 23:
				case 24:
					break;

				default:
					return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C41004), HttpStatus.OK);
			}
			// 易宝公众号支付需要传参userno
			if (requestPayModel.getPayType() == PayTypeEnum.T22.getCode()) {
				if (ParameterUtils.validParams(requestPayModel.getOpenId())) {
					//return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20102), HttpStatus.OK);
					return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20102,"公众号支付,缺少OPENID"), HttpStatus.OK);
				}
			}
			logger.error("支付USER_ID ：{}", requestPayModel.getUserId());
			Long userId = 0L;
			if (requestPayModel.getPayType() == PayTypeEnum.T23.getCode()) {//ONE KEY 一键支付
				
				String clientType = ClientType.APP;
				if(request.getHeader("phoneType") != null && request.getHeader("phoneType").length() > 0) {
					if(request.getHeader("phoneType").toLowerCase().equals(CommonConstants.PHONE_CLIENT_IOS) || request.getHeader("phoneType").toLowerCase().equals(CommonConstants.PHONE_CLIENT_ANDROID)){
						clientType = ClientType.APP;
					} else if( request.getHeader("phoneType").toLowerCase().equals(CommonConstants.PHONE_CLIENT_h5) || request.getHeader("phoneType").toLowerCase().equals(CommonConstants.PHONE_CLIENT_WX)) {
						clientType = ClientType.H5;
					}
					
				}
				
				if (!ParameterUtils.validParams(requestPayModel.getUserId())) {
					userId = requestPayModel.getUserId();
				}
				// userId前端没有传值，默认从Token中取，取不到说明没有登录
				if (userId.intValue() == 0) {
					String code = request.getHeader("userToken");
					if (StringUtil.isEmpty(code)) {
						return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20176), HttpStatus.OK);
					}
					Token token = tokenService.selectTokenByCode(code,clientType);
					if (token == null) {
						return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20176), HttpStatus.OK);
					}
					userId = token.getUserId();
				}
				if(userId == 0) {
					return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20177), HttpStatus.OK);
				}
			}
			
			String ipAddress = NetworkUtil.getRealIp(request);
			return this.orderPayService.goToSettleAccounts(userId, requestPayModel.getOrderSn(), requestPayModel.getPayType(), requestPayModel.getOpenId(), ipAddress);
		} catch (Exception e) {
			logger.error("获取支付异常：{}", e.getMessage(), e);
			return new ResponseEntity<>(new ResponseBaseModel(ErrorEnum.C20000), HttpStatus.OK);
		}
	}
}